package com.qfedu.openplateform.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.ResponseData;
import com.qfedu.openplateform.gateway.utils.Md5Util;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 签名过滤器
 *  防止被抓包 篡改数据
 */

public class SignFilter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // http://localhost:8099/login?username=admin&password=admin&time=2021:03:18 19:52:50&sign=abcdeeeeeeeee
        // 1.获取到 前端传递的签名   sign=abcdeeeeeeeee
        // 2.计算出来前端传递参数 除sign 之外的 服务器签名
//        username=admin&password=admin&time=2021:03:18 19:52:50 ----->serviceSign==xxxxx
        // 3.比较签  sign    serviceSign



        Map<String, String[]> map =  request.getParameterMap();
        Map<String, String> signMap = new HashMap<>();//用于保存除了签名之前的数据
        for (String key:map.keySet()) {
            if (!"sign".equalsIgnoreCase(key)) {  // 排除 sign   得到 username=admin&password=admin&time=2021:03:18 19:52:50
                signMap.put(key, request.getParameter(key));//保存除了sign之外的数据
            }
        }

        // 前端提交签名 比对  手动传
        String sign = request.getParameter("sign");

        // 将前端请求的 除了sign 参数组成map    "meiyoumima" 秘钥（盐）
        // 服务器签名
        String signServer = Md5Util.md5Signature(signMap,"meiyoumima");

        System.out.println("sign:"+sign+"--signServer:"+signServer);

        if (signServer.equals(sign)){
            return true;
        }


        response.setContentType("application/json;charset=utf-8");
        ResponseData bean = new ResponseData();
        bean.setCode(ExceptionDict.SYSTEMPARAM_IDEMPOTENTS_ERROR);
        bean.setMessage("签名错误");
        try {
            response.getWriter().println(JSON.toJSONString(bean));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        return false;



    }
}
